
from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader

from src.main.server.controller.login_controller import LoginController
from src.main.vision.windows.client_main_window import client_main_window
from src.main.vision.windows.client_register_window import client_register_window


class ClientLoginWindow:

    def __init__(self, main_window):
        self._load_ui()
        self.main_window = main_window

    def _load_ui(self):
        path = "../../../qt_ui/login.ui"
        file = QFile(path)
        try:
            loader = QUiLoader()
            self.window = loader.load(file)
            self.window.pushButton.clicked.connect(self.login_check)
            self.window.pushButton_3.clicked.connect(self.register)


        finally:
            file.close()

        if self.window:
            self.window.show()  # 显示独立窗口
        else:
            print("加载 UI 失败，请检查文件路径或内容")

    def login_check(self):
        """登录检查"""
        username = self.window.lineEdit.text()
        password = self.window.lineEdit_2.text()

        if username:
            print(f"用户输入的账号为：{username}")
        else:
            print("请输入账户名")
            return
        if password:
            print(f"用户输入的密码为：{password}")
        else:
            print("请输入密码")
            return

        result = LoginController().login(username, password)
        if result:
            print("登录成功")
            print("模拟进入用户界面")
            client_main_window(self, username)
            self.close_window()
        else:
            print("密码错误或账户不存在，请重新输入")

    def register(self):
        client_register_window(self)
        self.close_window()

    def close_window(self):
        """关闭当前窗口"""
        self.window.close()

def client_login_window(self):
        self.login_window = ClientLoginWindow(self)